import { Injectable } from '@nestjs/common';
import { Model } from 'mongoose';
import { InjectModel } from '@nestjs/mongoose';
import { Epg, EpgDocument } from '../../schema/epg.schema';
import * as dayjs from 'dayjs';

@Injectable()
export class EpgService {
  constructor(@InjectModel('Epg') private epgModel: Model<EpgDocument>) {}
  // 增加链接
  async addEpgPath(epgParams): Promise<any> {
    const result = await this.findEpgInfo(epgParams.pathAddress);
    const createTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
    epgParams.createTime = createTime;
    epgParams.id = new Date().getTime();

    let createEpg;
    if (!result) {
      createEpg = await new this.epgModel(epgParams).save();
      return {
        message: '添加成功！',
        code: '0',
        result: createEpg,
      };
    } else {
      return {
        message: '已存在相同入口地址！',
        code: '1',
        result: 'fail',
      };
    }
  }

  // 删除链接
  async removeEpgPath(query): Promise<any> {
    const result = await this.epgModel.deleteOne({ id: query.id });

    return {
      message: result.n == 1 ? '删除成功' : '删除失败',
      code: result.n == 1 ? '0' : '1',
      result: result.n == 1 ? 'ok' : 'fail',
    };
  }

  // 获取列表
  async getEpgList(): Promise<any> {
    const result = await this.epgModel.find().exec();

    return {
      code: 0,
      msg: '成功',
      count: result.length,
      data: result,
    };
  }

  // 查找指定链接
  async findEpgInfo(pathAddress: string): Promise<Epg> {
    return this.epgModel.findOne({ pathAddress: pathAddress }).exec();
  }
}
